package modular {
	import flash.display.Loader;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import ch.sfug.data.Set;
	import ch.sfug.log.Logger;
	import ch.sfug.net.loader.MediaLoader;
	import ch.sfug.net.loader.QueueLoader;
	
	import modular.module.PreloaderModule;	

	/**
	 * @author Administrator
	 */
	public class LibraryLoader extends EventDispatcher {

		private var queue:QueueLoader;
		private var _preloader:PreloaderModule;

		public function LibraryLoader() {
			
			queue = new QueueLoader();
			queue.addEventListener( Event.COMPLETE , onLoaded );
			queue.addEventListener( ErrorEvent.ERROR, onError );
			queue.addEventListener( ErrorEvent.ERROR, onError );
			queue.addEventListener( IOErrorEvent.IO_ERROR, onError );
			queue.addEventListener( SecurityErrorEvent.SECURITY_ERROR, onError );
		}

		
		
		public function loadLibraries( libs:Set ):void {
			
			queue.stop();
			queue.removeLoaders();
			
			for each( var url:String in libs.toArray() ) {
				
				var ml:MediaLoader = new MediaLoader( url );
				ml.context = new LoaderContext( false, new ApplicationDomain( ApplicationDomain.currentDomain ) );
				ml.addEventListener( ProgressEvent.PROGRESS, _preloader.libraryProgress );
				
				Logger.log( "load library: " + url, Modular.LOG_INFO );
				
				queue.addLoader( ml );
			}
			
			_preloader.show();
			queue.start();
			
		}
		
		private function onLoaded(event:Event):void {
			for each( var ml:MediaLoader in queue.loaders ) {
				Library.register( ml.getResult().contentLoaderInfo.applicationDomain, ml.request.url );
				ml.removeEventListener( ProgressEvent.PROGRESS, _preloader.libraryProgress );
			}
			_preloader.hide();
			dispatchEvent(event);
		}

		
		private function onError( event:ErrorEvent ):void {
			Logger.log( event.text, Modular.LOG_ERROR );
		}

		public function set preloader( pl:PreloaderModule ):void {
			if( _preloader != null ) queue.removeEventListener( ProgressEvent.PROGRESS, _preloader.queueProgress );
			_preloader = pl;
			queue.addEventListener( ProgressEvent.PROGRESS, _preloader.queueProgress );
		}
		
		public function get preloader( ):PreloaderModule {
			return _preloader;
		}
	}
}
